package org.itboys.shop.service;

import java.util.Date;
import java.util.List;

import org.itboys.commons.utils.random.RandomUtils;
import org.itboys.commons.utils.sms.SmsUtils;
import org.itboys.member.entity.mongo.MemberCode;
import org.itboys.member.service.MemberCodeService;
import org.itboys.shop.tools.SMSTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 验证码发送及校验
 * @author ok
 *
 */
@Service
public class CodeService {
	
	@Autowired
	private MemberCodeService memberCodeService;
	/**
	 * 发送验证码,成功返回true
	 * @param mobile
	 * @return
	 */
	public void sendCode(String mobile){
		String activeCode = RandomUtils.getIntRandom(6);
		MemberCode memberActiveCode = new MemberCode();
		memberActiveCode.setMemberId(0l);
		memberActiveCode.setCode(activeCode);
		memberActiveCode.setCreateTime(new Date());
		memberActiveCode.setValue(mobile);
		memberCodeService.save(memberActiveCode);
		SMSTool.send(mobile, "尊敬的美丽乡村用户，您的验证码为:"+activeCode+",请妥善保管，以免造成不必要的损失！");
	}
	/**
	 * 验证校验码   成功返回true
	 * @param mobile
	 * @param code
	 * @return
	 */
	public boolean validateCode(String mobile , String code){
		List<MemberCode> macs = memberCodeService
				.getRecentlyActiveCodeByValue(mobile, 5 * 60);
		if (!macs.isEmpty() && macs.size() > 0) {
			MemberCode mac = macs.get(0);
			if (mac.getCode().equals(code) && mac.getActiveTime() == null) {
				return true;
			}
		}
		return false;
	}
	
}
